import React, { useState, useEffect, useContext, useRef } from 'react';
import { Routes, Route, useNavigate, useLocation, Navigate } from 'react-router-dom';
import enUS from 'antd/es/locale/en_US';
import zhCN from 'antd/es/locale/zh_CN';
import moment from 'moment';
import 'moment/locale/zh-cn';
import { Button, Modal, Form, Input, message, ConfigProvider, Dropdown, Typography, Space, Spin } from 'antd';
import {
  AppstoreOutlined,
  ContainerOutlined,
  DownOutlined,
  HomeOutlined,
  MailOutlined,
  SettingOutlined
} from '@ant-design/icons';
import Cookies from 'js-cookie';
import { useTranslation } from 'react-i18next';

import routes from '@src/routes';
import { PublicDataStore } from '@src/store/PublicData/Provider';

import { login, register, getUserInfoApi, getForgotPasswordEmailCode, resetPasswordApi } from '@src/services/login';
import {
  getAllContinent,
  getAllCountry,
  getAllCity
} from '@src/services/biddingProject';
import { getCompanyInfo, getAllBusiness } from '@src/services/company';

import styles from './styles.module.less';
import { hasPermission } from "@src/services/auth";
import {MenuProps} from "antd";
import { Menu } from 'antd';
import { editUserLangApi } from '@src/services/user';

const { Text } = Typography;

const langMap = {
  'enUS': 'English',
  'zhCN': '简体中文'
}

const Layouts = () => {
  moment.locale('en');
  const { t, i18n } = useTranslation();
  const navigate = useNavigate();
  const location = useLocation();
  const formRef = useRef(null);
  const verifyCodeIntervalRef = useRef(null);
  const { state, dispatch } = useContext(PublicDataStore);

  const [menuDefaultSelected, setMenuDefaultSelected] = useState('/home');
  const [loginModalVisible, setLoginModalVisible] = useState(false);
  const [submitLoading, setSubmitLoading] = useState(false);
  // 暂时用作记录是否已登录状态
  const [isLogin, setIsLogin] = useState(false);
  const [utmInviteCode, setInviteCode] = useState(false);
  // 表单类型 login register forgot
  const [formType, setFormType] = useState('login');
  const [getCodeLoading, setGetCodeLoading] = useState(false);
  const [verifyCodeTime, setVerifyCodeTime] = useState(60);
  const [verifyCodeBtnLoading, setVerifyCodeBtnLoading] = useState(false);
  const [locale, setLocal] = useState(enUS);
  const [aiLang, setAiLang] = useState('enUS');
  const [loadingCompanyInfo, setLoadingCompanyInfo] = useState(true); // 新增加载状态
  const [language, setLanguage] = useState('English'); // 新增加载状态

  useEffect(() => {
    // const flag = Cookies.get('token');
    // const userId = Cookies.get('ai-user-id');
    const flag = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX2lkIjoxMywiZW1haWwiOiJqYW1lcy56b3UzNUBiaXRvc3MuY24ifQ.6Fh2MLlTn8sZOd7YxM-tmax3yfc09ZemvUL7Vf88yoU";
    const userId = "13";
    // if (flag && userId) {
      setIsLogin(true);
    // } else {
    //   Cookies.remove('token');
    //   Cookies.remove('ai-user-id');
    //   setIsLogin(false);
    // }

    // const urlParams = new URLSearchParams(window.location.search);
    // const utmInviteCode = urlParams.get('utm_invite_code');
    // if (!flag && utmInviteCode !== null) {
    //   setLoginModalVisible(true);
    //   setInviteCode(utmInviteCode);
    //   setFormType('login');
    // }

    // onGetAllContinentLoad();
    // onGetAllCountryLoad();
    // onGetAllCityLoad();
    // onGetAllBusiness();
    // onGetCompanyInfo();

    if (userId) {
      onGetUserInfo({
        user_id: userId
      });
    }

    return () => {
      clearInterval(verifyCodeIntervalRef.current)
    }
  }, []);

  useEffect(() => {
    const lang = sessionStorage.getItem('ai_lang') || 'enUS';

    onChangeSystemTranslation(lang);
  }, []);

  const onSelectMenu = (key) => {
    setMenuDefaultSelected(key);
    navigate(key.split('/*')[0]);
  };

  // 控制menu高亮
  useEffect(() => {
    const path = location.pathname;
    if (path === '/') {
      setMenuDefaultSelected(routes[0].link);
      return;
    }
    console.log(path)
    const routerFilter = routes.find(item => path.includes(item.link.split('/*')[0]));

    if (!routerFilter) {
      setMenuDefaultSelected(routes[0].link);
      return;
    }

    setMenuDefaultSelected(routerFilter.link);
  }, [location]);


  const onRegisterFinish = async (data) => {
    setSubmitLoading(true);

    const res = await register({
      email: data.email,
      invite_code: utmInviteCode === false ?  '': utmInviteCode,
    });

    setSubmitLoading(false);

    if (!res) return;

    message.success(res.message);

    setFormType('login');
  };

  const onLoginFinish = async (data) => {
    setSubmitLoading(true);

    const res = await login({
      email: data.email,
      password: data.password
    });

    setSubmitLoading(false);

    if (!res) return;

    message.success(t('Login successful'));

    Cookies.set('ai-user-id', res.user_id);
    onGetUserInfo({
      user_id: res.user_id
    });
    setIsLogin(true);
    onCancelLogin();
    onGetCompanyInfo();
  };

  const onCancelLogin = () => {
    setLoginModalVisible(false);
    setFormType('login');
    setSubmitLoading(false);
  };

  const onForgotPasswordFinish = async (data) => {
    setSubmitLoading(true);

    const res = await resetPasswordApi(data);

    setSubmitLoading(false);

    if (!res) return;
    message.success(res.message);
    setFormType('login');
  }

  const onGetCode = async () => {
    let email = formRef.current?.getFieldValue('email');
    if (!email) return;

    setGetCodeLoading(true);

    const res = await getForgotPasswordEmailCode({
      email
    });

    if (!res) return;

    message.success(res.message);
    setVerifyCodeBtnLoading(true);


    verifyCodeIntervalRef.current = setInterval(() => {
      setVerifyCodeTime((oldVal) => {
        if (oldVal > 1) return oldVal - 1;

        clearInterval(verifyCodeIntervalRef.current);
        setVerifyCodeBtnLoading(false);

        return 60;
      })
    }, 1000);
    setGetCodeLoading(false);
  }


  // 获取所有洲
  const onGetAllContinentLoad = async () => {
    const res = await getAllContinent();

    if (!res) return;

    dispatch({
      type: 'SET_CONTINENT',
      payload: res
    });
  }

  // 获取所有国家
  const onGetAllCountryLoad = async () => {
    const res = await getAllCountry();

    if (!res) return;

    dispatch({
      type: 'SET_COUNTRY',
      payload: res
    });
  }

  // 获取所有城市
  const onGetAllCityLoad = async () => {
    const res = await getAllCity();
    if (!res) return;

    dispatch({
      type: 'SET_CITY',
      payload: res
    });
  }

  // 获取所有业务范围
  const onGetAllBusiness = async () => {
    const res = await getAllBusiness();
    if (!res) return;

    dispatch({
      type: 'SET_ALL_BUSINESS',
      payload: res
    });
  }

  // 获取当前公司信息
  const onGetCompanyInfo = async () => {
    const res = await getCompanyInfo();

    if (!res) return;

    dispatch({
      type: 'SET_COMPANY_INFO',
      payload: res
    })
  }

  // 监听 state.companyInof 的变化
  useEffect(() => {
    setLoadingCompanyInfo(false); // 获取完公司信息后设置加载状态为false
  }, [state.companyInof]); // 监听 state.companyInof 变化


  // 请求当前用户信息
  const onGetUserInfo = async ({
    user_id
  }) => {
    const res = await getUserInfoApi({
      user_id
    });

    if (!res) return;

    onChangeSystemTranslation(res[0]?.lang);
    sessionStorage.setItem('ai_lang', res[0]?.lang);
    dispatch({
      type: 'SET_USER_INFO',
      payload: res[0] || {}
    })
  }

  const onLangChange = (key) => {
    setAiLang(key);
    setLanguage(key === 'enUS' ? '中文':'English');
    sessionStorage.setItem('ai_lang', key);
    onChangeSystemTranslation(key);
    editUserLangApi({
      lang: key
    });
  }

  const onChangeSystemTranslation = (key) => {
    setAiLang(key);
    i18n.changeLanguage(key);
    setLanguage(key === 'enUS' ? '中文':'English');

    switch (key) {
      case 'enUS':
        return setLocal(enUS);
      case 'zhCN':
        return setLocal(zhCN);
      default:
        return setLocal(enUS);
    }
  }


  type MenuItem = Required<MenuProps>['items'][number];

  function getItem(
      label: React.ReactNode,
      key?: React.Key | null,
      icon?: React.ReactNode,
      children?: MenuItem[],
      type?: 'group',
  ): MenuItem {
    return {
      key,
      icon,
      children,
      label,
      type,
    } ;
  }

  const items: MenuItem[] = [
    getItem(language, 'sub4',<ContainerOutlined  style={{ fontSize: '20px', color:'#847ea8' }}/>, [
      getItem('中文', 'zhCN'),
      getItem('English', 'enUS'),
    ]),
  ];

  const onClick: MenuProps['onClick'] = e => {
    onLangChange(e.key)
  };


  return (
    <ConfigProvider locale={locale}>
      <div className={styles.layout_box}>
        {
          !isLogin && (
            <div className={styles.logo_banner_box}>
              <div className={styles.logo}>
                <img src="/img/dcc_logo.gif" alt='' style={{ backgroundColor: "#d13d3d", borderRadius: '6px' }} />
              </div>
              <div className={styles.login_box}>
                <Button type="primary" onClick={() => setLoginModalVisible(true)}>{t('Log in now')}</Button>
              </div>
            </div>
          )
        }
        {
          isLogin && (
            <div className={styles.menu_box}>
              <div className={styles.logo_box}>
                {/*<img src="/img/logo.svg" alt='' />*/}
                <img src="/img/dcc_logo.gif" alt='' style={{ backgroundColor: "#d13d3d", borderRadius: '6px' }} />
              </div>
              <div className={styles.dividing_line} />
              {
               (
                  <ul className={styles.menu_list}>
                    {
                      routes.map(item => {
                        if (item.menuHidden) return null;

                        return (
                            item.title !== 'Language' ?
                              <li key={item.link} onClick={() => onSelectMenu(item.link)}
                                className={`${menuDefaultSelected === item.link ? styles.highlight : ''} ${'Sign up for membership' === item.title ? styles.member : ''} ${'Personal Center' === item.title ? styles.self_center : ''}`}>
                                <span className={styles.icon}>{item.icon}</span>
                                <span className={styles.title}>
                                  <Text style={{ width: '84%'}}  ellipsis={{  tooltip: { title: t(item.title), placement: 'topLeft' } }} >{t(item.title)}</Text>
                                </span>
                              </li>
                            :
                                <div className={styles.language}><Menu defaultSelectedKeys={aiLang} onClick={onClick} style={{ width: 100, backgroundColor: 'transparent' }}  mode="vertical"
                                    items={items.map(item => ({
                                      ...item,
                                      style: { ...item.style, border: 'none', background: 'none' },
                                    }))}

                                /> </div>
                        )
                      })
                    }
                  </ul>
                )
              }


            </div>
          )
        }
        <div className={styles.content_box} style={isLogin ? {} : { marginLeft: '0', marginTop: '40px' }}>
          <Routes>
            {
              routes.map(item => (
                <Route path={item.link} element={item.component} key={item.link}></Route>
              ))
            }
            <Route path="/" element={<Navigate to="/home" />} />
            <Route path="/*" element={<Navigate to="/home" />} />
          </Routes>
        </div>

        <Modal
          open={loginModalVisible}
          onCancel={onCancelLogin}
          footer={null}
          style={{ minWidth: 400, top: 140 }}
          bodyStyle={{
            paddingBottom: 0
          }}
        >
          <div className={styles.login_form_box}>
            <div className={styles.header_box}>
              {
                (formType !== 'login') && (
                  <span className={styles.back_login}>
                    <Button
                      type='link'
                      disabled={submitLoading}
                      onClick={() => {
                        setFormType('login');
                      }}
                    >{`< ${t('Back to login')}`}</Button>
                  </span>
                )
              }
              <span className={styles.title}>{formType === 'register' ? t('Welcome to register') : formType === 'forgot' ? t('Forget the password') : t('Login')}</span>
            </div>

            <Form
              layout='vertical'
              ref={formRef}
              onFinish={formType === 'register' ? onRegisterFinish : formType === 'forgot' ? onForgotPasswordFinish : onLoginFinish}
            >
              {
                (formType !== 'forgot') && (
                  <Form.Item
                    label={t('Email')}
                    name="email"
                    rules={[
                      {
                        required: true,
                        message: t('Please enter your email address')
                      },
                      {
                        type: 'email',
                        message: t('Please enter the correct email format')
                      }
                    ]}
                  >
                    <Input name="email" placeholder={t('Please enter your email address')} />
                  </Form.Item>
                )
              }
              {
                (formType === 'forgot') && (
                  <>
                    <Form.Item>
                      <Input.Group className={styles.email_box}>
                        <Form.Item
                          name="email"
                          label={t('Email')}
                          rules={[
                            {
                              required: true,
                              message: t('Please enter your email address')
                            },
                            {
                              type: 'email',
                              message: t('Please enter the correct email format')
                            }
                          ]}
                        >
                          <Input name="email" placeholder={t('Please enter your email address')} />
                        </Form.Item>
                        <Button
                          type="primary"
                          onClick={() => {
                            formRef.current.validateFields(['email'])
                            onGetCode();
                          }}
                          loading={getCodeLoading}
                          disabled={verifyCodeBtnLoading}
                        >
                          {
                            verifyCodeBtnLoading
                              ? `${verifyCodeTime} s`
                              : t('Get verification code')
                          }
                        </Button>
                      </Input.Group>
                    </Form.Item>
                    <Form.Item
                      label={t('Verification Code')}
                      name="verify_code"
                      rules={[
                        {
                          required: true,
                          message: t('Please enter the verification code')
                        }
                      ]}
                    >
                      <Input name="verify_code" placeholder={t('Please enter the verification code')} />
                    </Form.Item>
                  </>
                )
              }
              {
                (formType !== 'register') && (
                  <Form.Item
                    label={t('Password')}
                    name="password"
                    rules={[
                      {
                        required: true,
                        message: t('Please enter your password')
                      },
                    ]}
                  >
                    <Input.Password name="password" placeholder={t('Please enter your password')} />
                  </Form.Item>
                )
              }
              <div className={styles.submit_box}>
                <Button htmlType="submit" type='primary' loading={submitLoading}
                  style={{ width: 200 }}>{formType === 'register' ? t('Register Now') : formType === 'forgot' ? t('Submit') : t('Login')}</Button>
              </div>
              {/* {
              !isRegister && (
                <div className={styles.register_switch_box}>
                  <Button htmlType="submit" type="link" disabled={submitLoading}
                    onClick={() => setIsRegister(true)}>立即注册</Button>
                </div>
              )
            } */}

              <div className={styles.register_switch_box}>
                {
                  formType !== 'forgot' && (
                    <Button type="link" disabled={submitLoading}
                      onClick={() => setFormType('forgot')}>{t('Forget the password')}?</Button>
                  )
                }
                {
                  formType !== 'register' && (
                    <Button type="link" disabled={submitLoading}
                      onClick={() => setFormType('register')}>{t('Register Now')}</Button>
                  )
                }
              </div>
            </Form>
          </div>
        </Modal>
      </div>
    </ConfigProvider>
  )
};

export default Layouts;